// @ts-nocheck
import styles from './index.module.less';
import { IconCurlyBrackets } from '@codexteam/icons';
import { make } from '../../utils/dom';
import { MathfieldElement } from 'mathlive';

MathfieldElement.fontsDirectory = "/docx-vue/mathlive/fonts";
MathfieldElement.soundsDirectory = "/docx-vue/mathlive/sounds";

class Math {
    static get toolbox() {
        return {
            title: 'Math',
            icon: IconCurlyBrackets
        };
    }

    static get isReadOnlySupported() {
        return true;
    }

    constructor({ data, api, config, readOnly }) {
        this.data = {
            value: data.value,
        };

        this.api = api;

        this.readOnly = readOnly;

        this.config = config || {};

        this.wrapper = undefined;
        this.isEdit = false;
        this.mfe = null;
    }

    render() {
        this.wrapper = make('div', styles['cx-custom-math']);
        this.mfe = new MathfieldElement();
        this.mfe.value = this.data.value || this.config.default;
        this.mfe.readOnly = !this.isEdit;
        this.wrapper.append(this.mfe);

        // 创建保存和编辑按钮
        const controlBox = make('div', styles.controlBox);
        const saveBtn = make('div', styles.saveBtn, { innerText: "保存" });
        const editBtn = make('div', styles.editBtn, { innerText: '编辑' });
        if (this.isEdit) {
            saveBtn.style.display = 'inline-block';
        } else {
            editBtn.style.display = 'inline-block';
        }
        controlBox.append(saveBtn, editBtn);

        this.wrapper.append(controlBox);

        // 监听编辑和保存事件
        this.api.listeners.on(editBtn, 'click', () => {
            this.isEdit = true;
            this.mfe.readOnly = !this.isEdit;
            saveBtn.style.display = 'inline-block';
            editBtn.style.display = 'none';
        }, false)

        this.api.listeners.on(saveBtn, 'click', () => {
            this.isEdit = false;
            this.mfe.readOnly = !this.isEdit;
            saveBtn.style.display = 'none';
            editBtn.style.display = 'inline-block';
            this.data.value = this.mfe.value;
        }, false)




        this.mfe.addEventListener('input', (e) => {
            this.data.value = this.mfe.value;
        }, false);

        return this.wrapper;
    }

    save(blockContent) {
        return this.data
    }
}

export default Math